package mlz.b_bytestream;

import org.junit.Test;

import java.io.*;
import java.util.Arrays;

/*
    读和写入 字节数组
 */
public class AIPDemo03 {

    @Test
    public void write01() throws IOException {
        FileOutputStream fos = new FileOutputStream("d.txt");
        String str = "你好,你吃了吗?";
        //字符 -> 字节
        byte[] bs = str.getBytes();
        System.out.println(Arrays.toString(bs));

        //再存入文件中
        fos.write(bs);
    }

    @Test
    public void read01() throws IOException {
        FileInputStream fis = new FileInputStream("d.txt");
        //现在bs中暂时没有任何数据 -> 这只是一个假设值
        byte[] bs = new byte[50];
        int i = fis.read(bs);
        System.out.println("i:" + i);
        System.out.println(Arrays.toString(bs));
    }

    //优化read写法
    @Test
    public void read02() throws IOException {
        FileInputStream fis = new FileInputStream("d.txt");
        byte[] bs = new byte[5];
        int i;
        while((i = fis.read(bs)) != -1){
            System.out.println("i:" + i);
            System.out.println(Arrays.toString(bs));
        }
    }

    //字节数组 -> 带截取
    @Test
    public void write02() throws IOException {
        FileOutputStream fos = new FileOutputStream("d.txt",true);
        String str = "你好,你吃了吗?";
        //字符 -> 字节
        byte[] bs = str.getBytes();
        System.out.println(Arrays.toString(bs));

        //再存入文件中
        //fos.write(bs);

        //写入str中的部分内容给 -> 也就是做截取
        fos.write(bs,0,6);
    }

}












